package com.szml.interceptors;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.szml.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author limin
 * @date 2025-06-17 17:56
 * @description
 */
public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的令牌
        String token = request.getHeader("token");
        //验证token
        Map<String, Object> map = new HashMap<>();
        try {
            JWTUtils.verify(token); //验证令牌
            return true; //token校验通过，放行请求
        } catch (SignatureVerificationException e) {
            //签名异常
            e.printStackTrace();
            map.put("msg","无效签名");
        } catch (TokenExpiredException e){
            //token过期异常
            e.printStackTrace();
            map.put("msg","token过期");
        } catch (AlgorithmMismatchException e){
            //算法不匹配异常
            e.printStackTrace();
            map.put("msg","算法不一致");
        } catch (Exception e){
            e.printStackTrace();
            map.put("msg","token无效");
        }
        map.put("state", false);
        //通过response将map响应到前台(将map转为json)
        //@ResponseBody 底层用的jackson 进行json转换
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);

        return false; //token验证不通过
    }
}
